package cc.yuxiang;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.hotlcc.wechat4j.Wechat;
import com.hotlcc.wechat4j.handler.ReceivedMsgHandler;
import com.hotlcc.wechat4j.model.ReceivedMsg;
import com.hotlcc.wechat4j.model.UserInfo;
import com.hotlcc.wechat4j.util.StringUtil;

import cc.yuxiang.spider.SpiderMeizi;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import jodd.io.FileUtil;
import jodd.io.findfile.WildcardFindFile;
import lombok.Data;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.Synchronized;
import lombok.val;
import lombok.experimental.Accessors;
import lombok.extern.slf4j.Slf4j;

/**
 * 微信群飚车助手
 */
@Slf4j
//@Component
//@Order(1)
public class StartJob implements ApplicationRunner {
	private Wechat wechat;
	private final String picPath = "D:\\temp\\pic";
	private final Qun qun;

	@Override
	public void run(ApplicationArguments applicationArguments) throws Exception {
		CompletableFuture.runAsync(() -> {
			// 进行爬虫
			new SpiderMeizi(picPath).spider(2);
		});
	}

	@Synchronized
	@Scheduled(fixedDelay = 1000 * 5)
	public void send() throws IOException {
		if (wechat == null || !wechat.isOnline()) {
			log.info("发送信息,微信没有登陆");
			return;
		}
		if (qun.getWeQun() == null) {
			//记得把微信群添加到通讯录,不然获取不到
			qun.setWeQun(wechat.getContactList(true).stream().filter(c -> qun.getName().equals(c.getNickName())).collect(Collectors.toList()).get(0));
			log.info("初始化发送聊天群:{}", qun.getWeQun());
			return;
		}
		// 群上已经有两分钟没有说话了,活跃下气氛
		if (DateUtil.between(qun.getLastReceive(), new Date(), DateUnit.MINUTE) > 2) {
			// 获取到所有爬下来的图片
			val jpgs = WildcardFindFile.create().matchType(WildcardFindFile.Match.NAME).include("*.jpg").recursive(false).includeDirs(false).searchPath(picPath).findAll();
			log.info("图片数量:{}", jpgs.size());
			// 随机拿出来一张图片发送
			val randomEle = RandomUtil.randomEle(jpgs, 1);
			log.info("拿出随机图片:{}", randomEle.getAbsolutePath());
			val sendImage  = wechat.sendImageToUserName(qun.getWeQun().getUserName(), randomEle);
			log.info("发送信息结果:{}", sendImage);
			this.move(randomEle);
			qun.setLastReceive(new Date());
		} else {
			log.info("最后发送信息:{}", DateUtil.formatDateTime(qun.getLastReceive()));
		}
	}

	// 将图片移动到已经发送
	private void move(File randomEle) throws IOException {
		val sendDir = new File(picPath + "\\sended");
		if (!FileUtil.isExistingFolder(sendDir)) {
			FileUtil.mkdir(sendDir);
		}
		FileUtil.move(randomEle, sendDir);
	}

	{
		qun = new Qun("在座的各位都是高富帅").setLastReceive(new Date());
		wechat = new Wechat();
		wechat.addReceivedMsgHandler(new ReceivedMsgHandler() {
			@Override
			public void handleAllType(Wechat wechat, ReceivedMsg msg) {
				val contact = wechat.getContactByUserName(false, msg.getFromUserName());
				if ("在座的各位都是高富帅".equals(contact.getNickName())) {
					qun.setLastReceive(new Date());
				}
				val name = StringUtil.isEmpty(contact.getRemarkName()) ? contact.getNickName() : contact.getRemarkName();
				System.out.println(name + ": " + msg.getContent());
			}
		});
		wechat.autoLogin();
	}

	@Data
	@Accessors(chain = true)
	@RequiredArgsConstructor
	public static class Qun {
		// 群名称
		private @NonNull String name;
		private UserInfo weQun;
		// 最后发送时间
		private Date lastReceive;
	}

}